/**
 * @description 数据库公共部分抽取
 * @param {*} success 连接成功的回调
 * @param {*} error 连接失败的回调
 */

module.exports = function (success, error) {
  // error为空，则赋默认值
  if (typeof error !== "function") {
    error = () => {
      console.log("连接失败了");
    };
  }

  // 1.导入数据库
  const mongoose = require("mongoose");

  // 2.连接 MongDB 服务
  const { DB_HOST, DB_PORT, DB_NAME } = require("./databaseConfig");
  mongoose.connect(`mongodb://${DB_HOST}:${DB_PORT}/${DB_NAME}`);

  // 3.设置回调：成功的回调、失败的回调、关闭的回调
  mongoose.connection.once("open", () => {
    console.log("数据库连接成功");
    success();
  });

  mongoose.connection.on("error", () => {
    console.log("数据库连接失败");
    error();
  });
  
  mongoose.connection.on("close", () => {
    console.log("数据库关闭");
  });
};
